package com.hxs.learn.action.core;

import com.alibaba.fastjson.JSON;
import com.hxs.learn.common.entity.socket.SocketRequestMessage;
import com.hxs.learn.common.entity.socket.SocketResponseMessage;
import com.hxs.learn.common.result.Result;
import com.hxs.learn.common.web.LoginInfo;
import com.hxs.learn.common.web.annotation.Login;
import com.hxs.learn.constants.core.web.ReqConst;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author huxinsheng
 */
@RestController
@RequestMapping("core/socket")
public class WebSocketController extends AbstractViewAction {
    @RequestMapping(ReqConst.REQ_INDEX)
    public ModelAndView index(@Login LoginInfo loginInfo) {
        return createModelAndView(loginInfo);
    }

    @MessageMapping("/send")//浏览器向服务器发送请求时，通过MessageMapping映射/send地址
    @SendTo("/topic/getResponse")//当服务器有消息时，会对订阅了@SendTo中路径的浏览器发送消息
    public SocketResponseMessage say(SocketRequestMessage message) throws InterruptedException {
        return new SocketResponseMessage(JSON.toJSONString(Result.ok(message.getRequestMessage())));
    }
}
